import java.util.concurrent.FutureTask;

public class Comparison {
    public String Compare() {
        String[] sites = {"淘宝", "京东", "拼多多", "抖音商城", "苏宁易购"};//执行比价，从5个网站查询价格
        PriceCall priceCall = new PriceCall();
        FutureTask<PriceDelay>[] price = new FutureTask[5];
        for(int i = 0; i < 5; i++) {
            price[i] = new FutureTask<>(priceCall);
        }
        Thread[] site = new Thread[5];
        for (int i = 0; i < 5; i++) {
            site[i] = new Thread(price[i], sites[i]);
            site[i].start();
        }
        StringBuilder result = new StringBuilder();
        //用数组和循环存储价格
        double[] prices = new double[5];
        int[] delays = new int[5];
        String[] times = new String[5];
        int allresult = 0;
        try {
            for (int i = 0; i < 5; i++) {
                prices[i] = price[i].get().getPrice();
                delays[i] = price[i].get().getDelay();
                times[i] = price[i].get().getTime();
                result.append("查询时间" + times[i] + "\n" + sites[i] + "的价格为：" + prices[i] + "元(延迟" + delays[i] + "ms)\n\n");
            }
            allresult = priceCall.getResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取价格最低的网站
        double minPrice = prices[0];
        String minSite = sites[0];
        try {
            for (int i = 1; i < 5; i++) {
                if (prices[i] < minPrice) {
                    minPrice = prices[i];
                    minSite = sites[i];
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        result.append("\n一共查询了" + allresult + "条结果" + "\n价格最低的网站为：" + minSite + "\n价格为：" + minPrice + "元");
        return result.toString();
    }
}